package com.example.administrator.exkotlin.contentprovider

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import androidx.core.app.ActivityCompat
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.Toast
import com.example.administrator.exkotlin.R
import kotlinx.android.synthetic.main.activity_read_contact.*

/**
 * ContentProvider
 * 获取联系人
 * */
class ReadContactActivity : AppCompatActivity() {
    private val conttactList = ArrayList<String>()
    private val Permissions = arrayOf(android.Manifest.permission.READ_CONTACTS)
    private val mRquestCode = 1
    private lateinit var adapter: ArrayAdapter<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_read_contact)
        initDatas()
    }

    private fun initDatas() {
        //创建要给ArrayAdapter使用系统布局item，填入数据conttactList
        adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, conttactList)
        lv_contanct.adapter = adapter
        if (requstPermisions(Permissions)) {
            readContancts()
        }
    }

    /**
     * 参数详解：
     * uri：数据库的uri地址  Uri.parse("content://应用包名/表名")
     * projection：字符串数组 字段名
     * selection：字符串 传入列名=？ and 列名=？ 约束条件
     * selectionArg：{查询的具体数据}和selection要一 一对应。
     * sortOrder：//排序
     * cursor = resolver.query(uri, projection, projection , selectionArg, sortOrder);
     * */
    //通过ContentProvider获取联系人
    private fun readContancts() {
        Log.i(javaClass.simpleName, "通过ContentProvider获取联系人")
        val uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI
        contentResolver.query(uri, null, null, null, "display_name asc").apply {
            while (moveToNext()) {
                val name = getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
                val number = getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                conttactList.add("姓名：$name \n号码：$number")
            }
            //释放资源
            close()
        }
        //更新数据
        adapter.notifyDataSetChanged()
    }


    //请求权限
    private fun requstPermisions(permissions: Array<String>): Boolean {
        var result = true
        for (permission in permissions) {
            if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                result = false
            }
        }
        if (!result) {
            ActivityCompat.requestPermissions(this, Permissions, mRquestCode)
        }

        return result
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            mRquestCode -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    readContancts()
                } else {
                    //是否完全禁止弹出权限
                    if (!shouldShowRequestPermissionRationale(Permissions)) {
                        Toast.makeText(this, "请自行到设置中，手动打开权限", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this, "请再次同意权限才能使用拨号功能", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    /**
     * 再次申请权限时，是否需要声明
     * 是否完全禁止弹出权限申请
     * @param permissions
     * @return
     */
    private fun shouldShowRequestPermissionRationale(permissions: Array<String>): Boolean {
        for (permission in permissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                return true
            }
        }
        return false
    }
}
